#include <stdio.h>

union quantity
{   
  short count;
  float weight;
  float volume;
};


int main(void) {
  // 写法1
  union quantity q;
  q.count = 4;
  // 写法2 
  union quantity q1 = {
    .count = 4
  };
  // 写法3
  union quantity q3 = {4};
  printf("count is %i\n", q.count);
  // printf("weight is %f\n", q.weight); // undefined
  q.weight = 0.5;
  printf("weight is %f\n", q.weight);
  // ->运算符
  union quantity4 {
    short count;
    float weight;
    float volume;
  };
  union quantity4* ptr;
  ptr = &q;

  printf("%d\n", ptr->count); // 4
  // union的结构指针与它的属性有关
  // 当前那个属性能取到值,指针就是对应的数据类型
  union  foo
  {
    int a;
    float b;
  } x;
  int* foo_int_p = (int *)&x;
  float* foo_float_p = (float *)&x;
  x.a = 12;
  printf("%d\n", x.a);   
  printf("%d\n", *foo_int_p);
  x.b = 3.141592;
  printf("%f\n", x.b);
  printf("%f\n", *foo_float_p);

  typedef union
  {
    short count;
    float weight;
    float volume;
  } quantity5;
  // union 结构的好处是省内存
  // union的长度等于内部最长属性的长度
  return 0;
}